<template>
	<view class="content">

		<view id='contentView'>

			<view class="page-body">
				<view class="page-section page-section-gap">
					<map id="myMap" style="width: 100%; height: 300px;" scale='18' :latitude="latitude"
						:longitude="longitude" :markers="covers" @regionchange="regionchange">
					</map>
				</view>
			</view>


			<view>
				<view class="uni-list">
					<view class="uni-list-cell">
						<view class="propertyBox">

							<view class="uni-list-cell-left">
								<h4>当前课程:</h4>
							</view>
							<view class="uni-list-cell-db">
								<picker @change="bindPickerChange" :value="courseIndex" :range="courseNameArray">
									<view class="uni-input">{{courseNameArray[courseIndex]}}</view>
								</picker>
							</view>

						</view>

					</view>
				</view>
			</view>
			<h4>打卡地址: {{addressListZ1}}</h4>

			<h4>当前定位地址: {{newPath}}</h4>

			<h4>打卡范围: {{scope}}米</h4>


			<view class="propertyBox">
				<h4>每周打卡时间:</h4>

				<view class="uni-list-cell-db">

					<view class="propertyBox">
						<h4>星期:{{week}}</h4>

					</view>

				</view>

				<h4>时间:{{time}}</h4>

				<h4>-当前打卡状态: {{punchCardStatus}}</h4>

			</view>



			<button type="default" @click="UpdatePath">更新位置信息</button>

			<button type="default" @click="punchCard">打卡</button>


		</view>


		<view id='buttomNavigation'>

			<!-- 这是老师的页面 -->
			<view class="nav" @click="()=>{clickNavi('打卡')}">打卡</view>

			<view class="nav" @click="()=>{clickNavi('个人信息')}">个人信息</view>




		</view>
	</view>
</template>

<script>
	let thatBythis=null;
	var self, mapCtx
	export default {
		data() {
			return {
				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				addressListZ1: '测试',
				latitude: 39.909001165008085,
				longitude: 116.39742205097009,
				covers: [{
					latitude: 39.909,
					longitude: 116.39742,
					iconPath: '../../../static/location.png'
				}],
				scope: 0,
				courseNameArray: ["数据等待加载"],
				courseIndex: 0,
				studentAllCourse: [],
				time: '',
				week: '',
				newPath: "打卡之前请先更新地址",
				punchCardStatus: false,
			}
		},
		onLoad() {
			thatBythis=this;
			// 这里应该是尝试拉取数据的地方
			console.log("当前尝试拉取数据");
			// 获取当前map
			mapCtx = wx.createMapContext('myMap')


			uni.request({
				url: uni.getStorageSync('serviceIp') + '/student/getAllCourse',
				method: 'GET',
				header: {
					'user': uni.getStorageSync("user")
				},
				//请求成功后返回
				success: (res) => {
					// 请求成功之后将数据给Info

					if (res.data.status) {

						console.log('res get onLoad', res);

						let courseNameList = [];


						res.data.data.forEach(item => {
							courseNameList.push(item.courseInfo.courseName);
						})
                        console.log('courseNameList', courseNameList);
						thatBythis.courseNameArray = courseNameList;
						thatBythis.studentAllCourse = res.data;
						

						thatBythis.updateCourse(0, res.data)

					} else {

						uni.showToast({
							title: '获取课程失败!',
							//将值设置为 success 或者直接不用写icon这个参数
							icon: 'error',
							//显示持续时间为 2秒
							duration: 2000
						})

					}



				},
				fail: (res) => {
					console.log("查看fail返回的信息,", res);
				}
			});

		},
		onShow() {
			uni.hideTabBar({});
			this.getPosition();
			
			uni.request({
				url: uni.getStorageSync('serviceIp') + '/student/getAllCourse',
				method: 'GET',
				header: {
					'user': uni.getStorageSync("user")
				},
				//请求成功后返回
				success: (res) => {
					// 请求成功之后将数据给Info
			
					if (res.data.status) {
			
						console.log('res get onShow', res);
			
						let courseNameList = [];
			
			
						res.data.data.forEach(item => {
							courseNameList.push(item.courseInfo.courseName);
						})
						
						if(res.data.data.size()==0){
							courseNameList.push("无数据");
						}
						
			            console.log('courseNameList', courseNameList);
						thatBythis.courseNameArray = courseNameList;
						thatBythis.studentAllCourse = res.data;
						
			
						thatBythis.updateCourse(0, res.data)
			
					} else {
			
						uni.showToast({
							title: '获取课程失败!',
							//将值设置为 success 或者直接不用写icon这个参数
							icon: 'error',
							//显示持续时间为 2秒
							duration: 2000
						})
			
					}
			
			
			
				},
				fail: (res) => {
					console.log("查看fail返回的信息,", res);
				}
			});
			
		},
		methods: {
			UpdatePath() {

				uni.getLocation({
					type: 'wgs84',
					geocode: true, //设
					success: function(lb) {




						// 创建地图坐标对象
						var point = new plus.maps.Point(lb.longitude, lb.latitude);
						//静态方法，反向地理编码
						plus.maps.Map.reverseGeocode(point, {}, (event) => {
								var address = event.address; // 转换后的地理位置
								var point = event.coord; // 转换后的坐标信息
								var coordType = event.coordType; // 转换后的坐标系类型
								var reg = /.+?(省|市|自治区|自治州|县|区)/g;
								var addressList = address.match(reg).toString().split(",");
								//注意 因为存在直辖市， 当所在地区为普通省市时，addressList.length == 3，city = addressList[1];当所在地区为直辖市时addressList.length == 2，city = addressList[0];
								let city = addressList.length == 3 ? addressList[1] : addressList[0];

								let CityString = '';

								addressList.forEach(item => {
									CityString = CityString + item + "-";
								});

								thatBythis.newPath = CityString;
								console.log(this.newPath);


							},
							function(e) {
								console.log("失败回调", e);
							}
						);



					},
				})

			},
			punchCard() {
               console.log('punchCard');
				uni.getLocation({
					type: 'wgs84',
					geocode: true, //设
					success: function(lb) {
                        console.log('punchCard2',thatBythis.studentAllCourse);
						uni.request({
							url: uni.getStorageSync('serviceIp') + '/student/punchCard',
							method: 'POST',
							header: {
								'user': uni.getStorageSync("user")
							},
							data: {
								courseId: thatBythis.studentAllCourse.data[thatBythis.courseIndex].courseInfo
									.courseId,
								latitude: lb.latitude,
								longitude: lb.longitude,
							},
							//请求成功后返回
							success: (res) => {
								// 请求成功之后将数据给Info
                                console.log("打卡数据",res);
								if (res.data.status) {

									uni.showToast({
										title: '打卡成功!',
										//将值设置为 success 或者直接不用写icon这个参数
										icon: 'success',
										//显示持续时间为 2秒
										duration: 2000
									})
                                    
									uni.request({
										url: uni.getStorageSync('serviceIp') + '/student/getAllCourse',
										method: 'GET',
										header: {
											'user': uni.getStorageSync("user")
										},
										//请求成功后返回
										success: (res) => {
											// 请求成功之后将数据给Info
									
											if (res.data.status) {
									
												console.log('res get onLoad', res);
									
												let courseNameList = [];
									
									
												res.data.data.forEach(item => {
													courseNameList.push(item.courseInfo.courseName);
												})
									            console.log('courseNameList', courseNameList);
												thatBythis.courseNameArray = courseNameList;
												thatBythis.studentAllCourse = res.data;
												
												thatBythis.courseIndex=0;  
									
												thatBythis.updateCourse(0, res.data)
									
											} else {
									
												uni.showToast({
													title: '获取课程失败!',
													//将值设置为 success 或者直接不用写icon这个参数
													icon: 'error',
													//显示持续时间为 2秒
													duration: 2000
												})
									
											}
									
									
									
										},
										fail: (res) => {
											console.log("查看fail返回的信息,", res);
										}
									});


								} else {


									uni.showToast({
										title: res.data.message,
										//将值设置为 success 或者直接不用写icon这个参数
										icon: 'error',
										//显示持续时间为 2秒
										duration: 2000
									})

								}

							},
							fail: (res) => {
								console.log("查看fail返回的信息,", res);
							}
						});



					},
				})

			},
			updateCourse(e, res) {

				this.latitude = res.data[e].courseInfo.latitude;
				this.longitude = res.data[e].courseInfo.longitude;

				this.covers[0].latitude = res.data[e].courseInfo.latitude;
				this.covers[0].longitude = res.data[e].courseInfo.longitude;

				this.time = res.data[e].courseInfo.punchCardDate;
				this.week = res.data[e].courseInfo.punchCardWeek;
				this.scope = res.data[e].courseInfo.punchCardScope;
				this.punchCardStatus = res.data[e].ifPunchCard;
			},
			bindTimeChange(e) {
				console.log(e);
				this.time = e.target.value;
			},
			regionchange(event) {
				console.log('regionchange', event)
				if (event.type == 'regionchange') {
					this.getCenterLanLat()
				}

			},
			getCenterLanLat() {
				this.mapContext = uni.createMapContext("myMap", this);


				this.mapContext.getCenterLocation({
					type: 'wgs84',
					success: (res) => {
						let address = {
							latitude: res.latitude,
							longitude: res.longitude
						}
						this.longitude = address.longitude;
						this.latitude = address.latitude;

						// 创建地图坐标对象
						var point = new plus.maps.Point(address.longitude, address.latitude);
						//静态方法，反向地理编码
						plus.maps.Map.reverseGeocode(point, {}, (event) => {
								var address = event.address; // 转换后的地理位置
								var point = event.coord; // 转换后的坐标信息
								var coordType = event.coordType; // 转换后的坐标系类型
								var reg = /.+?(省|市|自治区|自治州|县|区)/g;
								var addressList = address.match(reg).toString().split(",");
								//注意 因为存在直辖市， 当所在地区为普通省市时，addressList.length == 3，city = addressList[1];当所在地区为直辖市时addressList.length == 2，city = addressList[0];
								let city = addressList.length == 3 ? addressList[1] : addressList[0];

								let CityString = '';

								addressList.forEach(item => {
									CityString = CityString + item + "-";
								});
								this.addressListZ1 = CityString;

								console.log("addressList", addressList, this.addressListZ1);

							},
							function(e) {
								console.log("失败回调", e);
							}
						);


						this.covers[0].longitude = address.longitude;
						this.covers[0].latitude = address.latitude;


						this.$emit('longLatDetail', address)
						console.log('已经更新完数据')
					},
					fail: (err) => {


					}
				})
			},
			getPosition() {
				const that = this;
				uni.getLocation({
					type: 'wgs84',
					geocode: true, //设
					success: function(lb) {
						console.log("位置信息", lb);
						console.log('当前位置的经度：' + lb.longitude);
						console.log('当前位置的纬度：' + lb.latitude);
						that.latitude = lb.latitude;
						that.longitude = lb.longitude;
						console.log(lb.longitude, lb.latitude);


						// 创建地图坐标对象
						var point = new plus.maps.Point(lb.longitude, lb.latitude);
						//静态方法，反向地理编码
						plus.maps.Map.reverseGeocode(point, {}, (event) => {
								var address = event.address; // 转换后的地理位置
								var point = event.coord; // 转换后的坐标信息
								var coordType = event.coordType; // 转换后的坐标系类型
								var reg = /.+?(省|市|自治区|自治州|县|区)/g;
								var addressList = address.match(reg).toString().split(",");
								//注意 因为存在直辖市， 当所在地区为普通省市时，addressList.length == 3，city = addressList[1];当所在地区为直辖市时addressList.length == 2，city = addressList[0];
								let city = addressList.length == 3 ? addressList[1] : addressList[0];

								let CityString = '';

								addressList.forEach(item => {
									CityString = CityString + item + "-";
								});
								that.addressListZ1 = CityString;

								console.log("addressList", addressList, that.addressListZ1);

							},
							function(e) {
								console.log("失败回调", e);
							}
						);


						that.covers[0].latitude = lb.latitude;
						that.covers[0].longitude = lb.longitude;
					},
				})
			},
			clickNavi(e) {

				console.log('查看当前点击事件', e);

				if (e == '个人信息') {

					uni.switchTab({
						url: 'userInfo'
					});


				} else if (e == '管理课程') {


					console.log("触发管理课程动作");

					uni.switchTab({
						url: 'createCouse',
						success: (res) => {
							// #ifdef APP-PLUS
							let page = getCurrentPages().pop(); //跳转页面成功之后
							if (!page) return;
							// page.loadData(); //如果页面存在，则重新刷新页面
							console.log("触发页面刷新");
							// #endif 
						}
					});

				} else if (e == '管理学生') {


					console.log("触发管理学生动作");

					uni.switchTab({
						url: 'couseStudentAdmin',
						success: (res) => {
							// #ifdef APP-PLUS
							let page = getCurrentPages().pop(); //跳转页面成功之后
							if (!page) return;
							// page.loadData(); //如果页面存在，则重新刷新页面
							console.log("触发页面刷新");
							// #endif 
						}
					});
				}


			},
			bindPickerChange(e) {

				console.log("查看参数", e.target.value);
				this.courseIndex = e.target.value;
				this.updateCourse(this.courseIndex, this.studentAllCourse)
			}

		}
	}
</script>

<style>
	.content {
		/* 这是指定布局为flex */
		display: flex;
		/* 这是指定布局排列方式 */
		flex-direction: column;

		min-height: 100vh;
		/*100vh == height:100%,元素撑开与屏幕等高*/
	}

	#contentView {
		flex: 1;

	}

	#buttomNavigation {
		width: 100%;
		height: 30px;
		border: 1px solid black;
		display: flex;
		flex-direction: row;
		display: flex;
	}

	.propertyBox {
		flex-flow: row;
		justify-content: flex-start;
		display: flex;
	}


	.nav {
		flex: 1;
		/*等分*/
		border: 1px solid red;
		font-size: 14px;
	}


	.scroll-Y {
		height: 300rpx;
	}

	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}

	.scroll-view-item {
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.scroll-view-item_H {
		display: inline-block;
		width: 100%;
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		font-size: 36rpx;
	}
</style>